// APP
// Main.html第一次点击对应Tab时候初始化页面
//if (window.plus) {
//    //ready();
//} else {
//    document.addEventListener('plusready', ready, false);
//}
// Web
$(function() {
	if (AGENT_CLIENT.WEB) {
		coinlistPageReady();
	} else if (AGENT_CLIENT.APP) {
		$(".main").css("padding-bottom", "2px");
		$(".top").css("bottom", "10px");
		$("#wrapper").css('bottom', "0px")
		document.addEventListener("netchange", function() {
			//获取当前网络类型
			var nt = plus.networkinfo.getCurrentType();
			// 联网状态
			if ([plus.networkinfo.CONNECTION_ETHERNET, plus.networkinfo.CONNECTION_WIFI, plus.networkinfo.CONNECTION_CELL2G, plus.networkinfo.CONNECTION_CELL3G, plus.networkinfo.CONNECTION_CELL4G].indexOf(nt) > -1) {
				plus.webview.currentWebview().reload();
			}
		}, false);
	}
});
var _coinlistPage;
// 初始化方法
function coinlistPageReady() {
	$.getScript("http://pv.sohu.com/cityjson?ie=utf-8").fail(function (res) {
		$.toast(ERROR_MESSAGE.network);
	});
	var _main = ("fixed" == $(".main").css("position")) ? $(".main") : $(window);
	var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
	var _contentheight = ($(window).height() - CONFIG_MANAGER.headerHight);
	// IScroll
	// _loadingStep: 加载状态0默认，1显示加载状态，2执行加载数据，只有当为0时才能再次加载，这是防止过快拉动刷新
	var _myScroll, _pullDownEl, _pullDownL, _pagecount = 1,
		_loadingStep = 0;
	var _hotfansScroll, _newfansScroll;
	var coinlistPage = function() {
		this.init();
	};
	coinlistPage.prototype = {
		// 初始化页面
		init: function() {
			this.initIscroll();
			this.loadData();
			this.bindEvent();
		},
		// 加载数据
		loadData: function() {
			this.showCoinDiv();
			this.getCoin();
			this.loadCategory();
			this.loadexchange();
			this.loadFans();
			this.loadgoods();
		},
		// 绑定事件
		bindEvent: function() {
			var model = this;
			$("#btncamera").on("click", function() {
				_currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
				if (!_currentloginuser) {
					redirect("../account/login.html?backurl=mine/showpublish.html");
					return;
				} else {
					redirect("../mine/showpublish.html");
				}
			});
			//登录
			$("#span_login").on("click", function(){
				redirect("../account/login.html?backurl=coin|coinlist.html");
			});
			// 跳转消息页
			$("#btnmsg").on("click", function() {
				redirect("../message/messagelist.html");
			});
			// 置顶
			$("#gotop").on("click", function() {
				_myScroll.scrollTo(0, 0, 800);
			});
			// 星粉秀
			$("#fanslistdiv").on("click", "div[name=fansshow] img", function() {
				var id = $(this).attr("tip");
				if (id && id != "-1") {
					redirect("coindetail.html?id=" + id);
				}
			});
			// 商品类型
			$("#goodstypetabdiv").on("click", " li", function() {
				var tip = $(this).attr("tip");
				var activeItem = $(this);
				activeItem.addClass("current");
				var windowsWidth = $(window).width();
				var pleft = $(this).offset().left;
				if (pleft > (windowsWidth / 2)) {
					var le = pleft - (windowsWidth * 0.2);
					$("#goodstypetabdiv").animate({
						scrollLeft: ($("#goodstypetabdiv").scrollLeft() + le) + 'px'
					}, 300);
				} else if (pleft < 0) {
					var le = pleft - (windowsWidth * 0.2);
					$("#goodstypetabdiv").animate({
						scrollLeft: ($("#goodstypetabdiv").scrollLeft() + le) + 'px'
					}, 300);
				}
				redirect("../goods/goodslist.html?type=1&catalog=" + $(this).attr("tip"), false, "pop-in", function() {
					activeItem.removeClass("current");
				});
			});
			// 星兑换
			$(".main").on("click", "img[id^=adsF]", function() {
				var link = $(this).attr("link");
				if (link) {
					if (link.indexOf("http") > -1) {
						redirect(link);
					} else {
						redirect("../" + link);
					}
				}
			});
			// 星币范围
			$("#coinRangelist li").on("click", function() {
				var tip = $(this).children("a").attr("tip");
				var activeli = $('#coinRangelist a[class=active]');
				if (activeli.attr("tip") == tip) {
					return;
				}
				activeli.removeClass("active");
				$(this).children("a").addClass("active");

				$.showWaiting();
				model.loadgoods();
			});
			// 跳转商品详情
			$("#goodslist").on("click", "li", function() {
				redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
			});
			// 金币领取页
			$("#getcoindiv").on("click", function() {
				$(this).fadeOut(1500);
			});
			// 懒加载
			$('img.lazy').lazyload({
				threshold: 100,
				failure_limit: 10
			});
		},

		// 领取星币
		getCoin: function() {
			_currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
			if (!_currentloginuser) {
				return;
			}
			// 今日是否领取
			$.ajax({
				headers: {
					token: _currentloginuser.token
				},
				type: "GET",
				url: CONFIG_MANAGER.RequstUrl + "v1/member/coin/make/" + _currentloginuser.id + "/6"
			}).done(function(res) {
				_todayTakeCoin = true;
				if (!res.today_is_received) {
					$("#getcoindiv").fadeIn(100);
					if (AGENT_CLIENT.APP) {
						var p = plus.audio.createPlayer("_www/audio/coin.mp3");
						p.play(function() {

						}, function(e) {});
						plus.webview.getWebviewById("../mine/mylife.html").evalJS("reloadPage()");
					}
				}
				// 计算宽度
				$("#coinnum").text(res.latest_payin);
				$("#tomorrow_payin").text(res.tomorrow_payin);
				$("#totalcoin").text(res.latest_coin);
				_currentloginuser["coin"] = res.last_coin;
				setLocalStorage(STORAGE_MANAGER.user, _currentloginuser);
			}).fail(function(res) {
				var response = JSON.parse(res.responseText);
				if (response.Message && response.Message.indexOf("票据") > -1) {
					$.alert("你的帐号已经在其他地方登录", function() {
						clearLocalStorage();
						redirect("../account/login.html");
						return;
					});
				}
				$.toast(ERROR_MESSAGE.network);
			}).always(function() {
				setTimeout(function() {
					$("#getcoindiv").fadeOut(1500);
				}, 3000);
			});
		},
		//根据用户显示隐藏
		showCoinDiv: function() {
			var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
			if (_currentloginuser) {
				$("#showCoinCount_login").show();
				$("#showCoinCount_unlogin").hide();
			} else {
				$("#showCoinCount_login").hide();
				$("#showCoinCount_unlogin").show();
			}
		},
		// 获取分类
		loadCategory: function() {
			var model = this;

			// 读取缓存
			var categorycachedata = getLocalStorage(STORAGE_MANAGER.parentcategory);
			if (categorycachedata) {
				model.paintPage(categorycachedata);
				return;
			}

			$.ajax({
				type: "GET",
				url: CONFIG_MANAGER.RequstUrl + "v1/basic/category/child/0"
			}).done(function(res) {
				var list = res;
				model.paintPage(list);
				setLocalStorage(STORAGE_MANAGER.parentcategory, res);
			});
		},
		// 画页面
		paintPage: function(list) {
			var html = [];
			html.push(" <li tip='all'>所有分类</li>");
			$.each(list, function(i, item) {
				html.push(" <li tip='" + item.code + "'>" + item.name + "</li>");
			});
			$("#goodstypetab").html(html.join(""));
			// 计算Tab宽度
			var goodstypetabWidth = 0;
			$("#goodstypetab li").each(function() {
				goodstypetabWidth = goodstypetabWidth + ($(this).width() + 16);
			});
			$("#goodstypetab").width(goodstypetabWidth + 10);
			$("#goodstypewrapper").height(30); // 计算wrapper高度
			$("#goodstypescroller").width(goodstypetabWidth + 10);
			var goodstypescroller = new IScroll('#goodstypewrapper', {
				scrollX: true,
				scrollY: false,
				mouseWheel: true,
				click: true
			});
		},
		// 星兑换
		loadexchange: function() {
			var model = this;
			$.ajax({
				type: "GET",
				url: CONFIG_MANAGER.RequstUrl + "v1/ads/locatins/[APP-Coin]"
			}).done(function(res) {
				if (res) {
					model.setAdsImg(res);
				}
			}).fail(function(res) {
				//$.toast(ERROR_MESSAGE.network);
			});
		},
		// 设置首页广告图
		setAdsImg: function(locatins) {
			var adsimglist = $("img[id^=adsF]");
			for (var i = 0; i < adsimglist.length; i++) {
				var adsimg = $(adsimglist[i]);
				var id = adsimg.attr("id");
				var tag = id.substr(3);
				var urllist = locatins[tag];
				var imgsrc = (urllist.length > 0) ? urllist[0].path : "../../images/grey.gif";
				var imglink = (urllist.length > 0) ? urllist[0].link : "";
				// 获取图片尺寸
				var imgwidth = 114,
					imgheight = 114;
				var sizestr = adsimg.attr("size");
				if (sizestr) {
					var size = sizestr.split('*');
					if (size.length == 2) {
						imgwidth = size[0];
						imgheight = size[1];
					}
				}
				adsimg.attr({
					"data-original": getImageUrl(imgsrc, imgwidth, imgheight),
					link: imglink
				});
			}
		},
		// 获取星粉秀
		loadFans: function() {
			var model = this;
			var newfans = $.ajax({
				type: "GET",
				url: CONFIG_MANAGER.RequstUrl + "v1/fans/rank/1/20"
			});
			var hotfans = $.ajax({
				type: "GET",
				url: CONFIG_MANAGER.RequstUrl + "v1/fans/rank/2/20"
			});
			$.when(newfans, hotfans).done(function(res1, res2) {
				model.paintFanslist(res1, res2);
			});
		},
		// 画星粉秀
		paintFanslist: function(res1, res2) {
			var newfanslist = res1[0];
			var hotfanslist = res2[0];
			var html = [];
			html.push("<h2 class='mkbiaoti'><em>星粉秀</em></h2>");
			// 主图展示
			var mainShowCount = 4;
			var mainShowHtml = [];
			var mainShowTemplate = "<li><img class='lazy' name='mainshowimg' size='675*675' src='../../images/place/675x675.png' data-original='' /></li>";
			for (var i = 0; i < mainShowCount; i++) {
				mainShowHtml.push(mainShowTemplate)
			}
			html.push("<div class='banner xfxdtu mtb5' name='fansshow'><div class='slider'><ul>" + mainShowHtml.join("") + "</ul></div></div>");
			html.push("<div class='xfxxtu mtb5'  name='fansshow'>");
			html.push("<dl class='xfxnr1'> <dt><img class='lazy'  name='mainshowimg' size='330*330'   src='../../images/place/330x330.png'  data-original='' /></dt><dd class='xfxdtubt xfxdtubt1'><a></a></dd></dl>");
			html.push("<dl class='xfxnr1 ptop5'><dt><img class='lazy'  name='mainshowimg' size='330*330'  src='../../images/place/330x330.png'  data-original='' /></dt><dd class='xfxdtubt xfxdtubt1'><a></a></dd></dl>");
			html.push("</div>");
			html.push("<div style='clear: both;'></div>");
			$("#fanslistdiv").html(html.join(""));
			var mainShowList = $("#fanslistdiv img[name=mainshowimg]");
			var newfaslistlength = newfanslist.length;
			for (var i = 0; i < (mainShowCount + 2); i++) {
				if (i > (newfaslistlength - 1)) {
					break;
				}
				var currentMainShow = $(mainShowList[i]);
				var currentFansShow = newfanslist[i];
				var size = currentMainShow.attr("size").split('*');
				var pic = (currentFansShow.albums && currentFansShow.albums.length > 0) ? currentFansShow.albums[0].photo : ""
				currentMainShow.attr({
					"data-original": getImageUrl(pic, size[0], size[1]),
					"tip": currentFansShow.id
				});
				currentMainShow.parents("dl[class=xfxnr1]").find("a").text(currentFansShow.memo);
			}
			// 星粉秀主图展示
			$(".slider").touchSlider({
				width: $(window).width() * 0.625,
				height: $(window).width() * 0.625,
				during: 5000,
				autoplay: false,
				move: function(currindex, total) {
					if (currindex < total && newfanslist.length > currindex) {
						$("#coinshowdesc").text(newfanslist[currindex].memo);
					}
				}
			});
			var firstmemo = newfanslist && newfanslist.length > 1 ? newfanslist[0].memo : "";
			var coinshowdesc = $("<div class='coin-show-desc' id='coinshowdesc'></div>").width($(".focus").width()).text(firstmemo);
			$(".slider").append(coinshowdesc);

			html = [];
			// 最热和最新
			html.push("<div class='mtb5'>");
			html.push("<p class='zxandzrbt'>最新和最热门</p>");
			html.push("<div id='newfanswrapper' class='wrapper'><div id='newfanscroller' class='scroller'>")
			html.push("<div id='newfanslistdiv' class='horizontalScroll'>");
			html.push("<div class='zxandzr' name='fansshow'>");
			html.push("<dl class='xfxnr1 ptop5 mleft10'><dt><img src='../../images/zxtu1.jpg' /></dt></dl>");
			// 最新星粉秀
			$.each(newfanslist, function(i, item) {
				var pic = (item.albums && item.albums.length > 0) ? item.albums[0].photo : ""
				html.push("<dl class='xfxnr1 ptop5'><dt><img tip='" + item.id + "'  class='lazy' src='../../images/place/220x220.png' data-original='" + getImageUrl(pic, 220, 220) + "' /></dt><dd class='xfxdtubt xfxdtubt1'><a>" + item.memo + ".</a></dd></dl>");
			});
			html.push("<div style='clear: both;'></div><p class='zrfxs mbbottom'></p>");
			html.push("</div></div></div></div>");
			html.push("<div id='hotfanswrapper' class='wrapper'><div id='hotfanscroller' class='scroller'>")
			html.push("<div id='hotfanslistdiv' class='horizontalScroll'>");
			html.push("<div class='zxandzr' name='fansshow'>");
			html.push("<dl class='xfxnr1 ptop5 mleft10'> <dt><img src='../../images/zrtu1.jpg' /></dt></dl>");
			// 最热星粉秀
			$.each(hotfanslist, function(i, item) {
				var pic = (item.albums && item.albums.length > 0) ? item.albums[0].photo : ""
				html.push("<dl class='xfxnr1 ptop5'><dt><img tip='" + item.id + "' class='lazy'  src='../../images/place/220x220.png' data-original='" + getImageUrl(pic, 220, 220) + "' /></dt><dd class='xfxdtubt xfxdtubt1'><a>" + item.memo + ".</a></dd></dl>");
			});
			html.push("<div style='clear: both;'></div><p class='zrfxs mbbottom'></p>");
			html.push("</div></div></div></div>");
			html.push("</div>");
			$("#fanslistdiv").append(html.join(""));
			// 最新最热星秀
			var zxandzrdlwidth = $(window).width() * 0.225;
			$(".zxandzr dl").width(zxandzrdlwidth);
			$("#newfanswrapper").height(100); // 计算wrapper高度
			$("#hotfanswrapper").height(100); // 计算wrapper高度
			$("#newfanscroller").width((zxandzrdlwidth + 5) * (newfanslist.length + 1) + 15);
			$("#hotfanscroller").width((zxandzrdlwidth + 5) * (hotfanslist.length + 1) + 15);
			$("#newfanslistdiv .zxandzr").width((zxandzrdlwidth + 5) * (newfanslist.length + 1) + 15);
			$("#hotfanslistdiv .zxandzr").width((zxandzrdlwidth + 5) * (hotfanslist.length + 1) + 15);

			_newfansScroll = new IScroll('#newfanswrapper', {
				scrollX: true,
				scrollY: false,
				mouseWheel: true,
				probeType: 1
			});
			_hotfansScroll = new IScroll('#hotfanswrapper', {
				scrollX: true,
				scrollY: false,
				mouseWheel: true,
				probeType: 1
			});
			_myScroll.refresh();
			// 懒加载
			$('img.lazy').lazyload({
				threshold: 100,
				failure_limit: 10
			});
		},
		// 获取兑换列表
		loadgoods: function() {
			var postdata = {
				index: 1,
				search: {
					source: 3
				},
				size: 16,
				sorting: {
					new: "DESC"
				}
			};
			var activeli = $('#coinRangelist a[class=active]');
			if (activeli) {
				postdata.search["coin"] = activeli.attr("tip");
			}
			var thisPage = this; // 分类页           
			$.ajax({
				headers: {
					'Content-Type': 'application/json'
				},
				type: 'POST',
				url: CONFIG_MANAGER.RequstUrl + "v1/goods/search/promogoods",
				data: JSON.stringify(postdata)
			}).done(function(res) {
				var goodslist = (res && res.result) ? res.result : [];
				$("#goodslist").html("");
				if (goodslist.length == 0) {
					$("#nodatamessge").show();
					return;
				} else {
					$("#nodatamessge").hide();
				}
				thisPage.paintgoodslist(goodslist);
				_myScroll.refresh();
			}).fail(function() {}).always(function() {
				$.closeWaiting();
			});
		},
		// 画商品列表
		paintgoodslist: function(goodslist) {
			var html = [];
			$.each(goodslist, function(i, goodsitem) {
				html.push("<li class='syxhd' tip='" + goodsitem.sku_id + "'><dl>");
				html.push("<dt><img class='lazy' data-original='" + getImageUrl(goodsitem.logo, 500, 500) + "' src='../../images/place/500x500.png''></dt>");
				html.push("<dd>" + goodsitem.name + goodsitem.specs + "</dd>");
				if (goodsitem.Is_coin == 1) {
					html.push("<dd class='spjge mtop5'><span class='money'>￥" + goodsitem.sku_actprice + "</span>+<span class='jinbi'><b><img src='../../images/jbtub.jpg'></b>" + goodsitem.coin + "</span></dd>");
				} else {
					html.push("<dd class='xhmony'>￥" + goodsitem.shop_price + "</dd>");
				}
				html.push("</dl></li>");
			});
			$("#goodslist").html(html.join(""));
			$('img.lazy').lazyload({
				event: "scroll",
				threshold: 100,
				container: $("#goodslist"),
				failure_limit: 10
			});
		},
		// 判断显示置顶图标
		isDisplayTopIcon: function(y) {
			var top = (y * -1);
			if (top > _contentheight / 2) {
				$('#gotop').show();
			} else {
				$('#gotop').hide();
			}
		},
		// 初始化Iscroll
		initIscroll: function() {
			var thisPage = this;
			_pullDownEl = $('#pullDown');
			_pullDownL = _pullDownEl.find('.pullDownLabel');

			_myScroll = new IScroll('#wrapper', {
				probeType: 2,
				scrollbars: true,
				mouseWheel: false,
				fadeScrollbars: true,
				bounce: true,
				interactiveScrollbars: false,
				click: true,
				disableMouse: true,
				disablePointer: true
			});

			//滚动时
			_myScroll.on('scroll', function() {
				if (_loadingStep == 0 && !_pullDownEl.attr('class').match('flip|loading')) {
					if (this.y > 5) {
						//下拉刷新效果
						_pullDownEl.attr('class', "flip")
						_pullDownEl.show();
						_myScroll.refresh();
						_pullDownEl.addClass('flip');
						_pullDownL.html('松开刷新');
						_loadingStep = 1;
					}
				}
			});

			//滚动完毕
			_myScroll.on('scrollEnd', function() {
				if (_loadingStep == 1) {
					if (_pullDownEl.attr('class').match('flip|loading')) {
						_pullDownEl.removeClass('flip').addClass('loading');
						_pullDownL.html('正在刷新...');
						_loadingStep = 2;
						pullDownAction();
					}
				}

				// 判断是否显示置顶
				thisPage.isDisplayTopIcon(this.y);

				// 懒加载
				$('img.lazy').lazyload({
					threshold: 100,
					failure_limit: 10
				});

				_myScroll.refresh();
			});

			// 下拉刷新
			function pullDownAction() {
				setTimeout(function() {
					_pagecount = _pagecount + 1;
					refreshPage();
					_pullDownEl.hide();
					_pullDownEl.removeClass('loading');
					_pullDownL.html('下拉刷新');
					_myScroll.refresh();
					_loadingStep = 0;
				}, 1000);
			}

			// 刷新页面
			function refreshPage() {
				var adsimglist = $("img[id^=adsF]");
				for (var i = 0; i < adsimglist.length; i++) {
					var adsimg = $(adsimglist[i]);
					// 获取图片尺寸
					var imgwidth = 114,
						imgheight = 114;
					var sizestr = adsimg.attr("size");
					if (sizestr) {
						var size = sizestr.split('*');
						if (size.length == 2) {
							imgwidth = size[0];
							imgheight = size[1];
						}
					}
					adsimg.attr({
						"src": "../../images/place/" + imgwidth + "x" + imgheight + ".png"
					});
				}

				thisPage.getCoin();
				thisPage.loadexchange();
				thisPage.loadFans();
			}

			document.addEventListener('touchmove', function(e) {
				e.preventDefault();
			}, false);
		}
	};
	_coinlistPage = new coinlistPage();
}

//  触发当前页
function activePage() {
	$.getScript("http://pv.sohu.com/cityjson?ie=utf-8").fail(function (res) {
		$.toast(ERROR_MESSAGE.network);
	});
	_currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
	console.log('active_coinlist' + ' _todayTakeCoin:' + _todayTakeCoin + ' _coinlistPage:' + _coinlistPage);
	if (_coinlistPage) {
		_coinlistPage.showCoinDiv();
		if (!_todayTakeCoin) {
			_coinlistPage.getCoin();
		}
	}
}

var _todayTakeCoin = false;
// 刷新页面
function reloadPage() {
	if(_coinlistPage){
		_coinlistPage.loadData();
	}
	
}